package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"store-management/models"
)

type StoreControllers struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *StoreControllers) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	title := c.GetString("title")
	address := c.GetString("address")
	cate := c.GetString("cate")

	store := models.Store{
		Model:   gorm.Model{},
		Title:   title,
		Address: address,
		Cate:    cate,
	}

	err := models.DB.Create(&store).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "添加失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		_ = c.ServeJSON()
	}
}

func (c *StoreControllers) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var store []models.Store
	err := models.DB.Find(&store).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "查询失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: store,
		}
		_ = c.ServeJSON()
	}
}

func (c *StoreControllers) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id := c.GetString("id")

	err := models.DB.Delete(&models.Store{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "删除失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		_ = c.ServeJSON()
	}
}

func (c *StoreControllers) Update() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	address := c.GetString("address")
	cate := c.GetString("cate")

	store := models.Store{
		Model: gorm.Model{
			ID: uint(id),
		},
		Title:   title,
		Address: address,
		Cate:    cate,
	}

	err := models.DB.Updates(&store).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "修改失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		_ = c.ServeJSON()
	}
}
